﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Blog.TemplateEngine.Helpers;

namespace Blog.TemplateEngine.Functions
{
    class IfFunction : IFunction
    {
        protected INode Compile(Parser parser, Token token)
        {
            string[] source = token.Content.SplitAndTrim(' ');
            if (source.Length != 2)
            {
                throw new TemplateException("'ifnot' statements should 1 parameter: ifnot 'variable'");
            }

            NodeList body = parser.Parse(new string[] { "end" });
            parser.DeleteNextToken();

            return new IfNode(body, source[1]);
        }

        INode IFunction.Compile(Parser parser, Token token)
        {
            return Compile(parser, token);
        }
    }

    class IfNode : INode
    {
        NodeList mBody;
        string mVariable;

        public IfNode(NodeList body, string variable)
        {
            mBody = body;
            mVariable = variable;
        }

        protected string Render(Context context)
        {
            bool? value = VariableResolver.Resolve(context, mVariable) as bool?;
            if(value != null)
            {
                if((bool)value)
                {
                    return mBody.Render(context);
                }
            }

            return String.Empty;
        }

        string INode.Render(Context context)
        {
            return Render(context);
        }
    }
}
